import wsgiref.handlers

from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from BeautifulSoup import BeautifulSoup
from xmw.tianya.bot import *

from xmw import tianya
import xmw
from xmw import error
import os
import urllib2, urllib
import uuid

from google.appengine.ext import webapp


class MainPage(xmw.RequestHandler):


    def get_thread(self, status):
        q = tianya.TianyaThread.all()
        q.filter('status = ', status)
        thread = q.get()
        return thread
        
    def get(self):
        """
        Step1:
            1.search INIT thread
            2.if not exist,search RUN Thread
            3.if not exist,search SYN Thread
        Step2:
            get thread info,and save it into db
        """
                
        
        
        thread = self.get_thread(xmw.Thread_Status.INIT)
        
        
        if thread is not None:
            thread.on_INIT() 
            thread.put()
            template_values = { "thread":thread }
            self.render_template(template_values, 'thread')            
            return
        
        thread = self.get_thread(xmw.Thread_Status.RUN)
          
              
        if thread is not None:
            thread.on_RUN()
            thread.put()
            template_values = { "thread":thread }
            #print "--------"
            #print 'thread22 =%s' % thread.lst_page_url 
            self.render_template(template_values, 'thread')            
            return
        

        thread = self.get_thread(xmw.Thread_Status.SYN)
        
        if thread is not None:
            thread.on_SYN()
            if thread.status == xmw.Thread_Status.RUN:
                thread.put()
            template_values = { "thread":thread }
            self.render_template(template_values, 'thread')            
            return

        e = xmw.error.NO_THREAD_TO_TRACE("")
        self.render_error(e)
        return
    
def main():
    application = webapp.WSGIApplication(
                                       [('/robot/scan_thread', MainPage)],
                                       debug=True)
    wsgiref.handlers.CGIHandler().run(application)

if __name__ == "__main__":
  main()
